/**
 * 按需维保，维保单位可申请按需维保申请，由区级单位审批
 */
import {Component, NgModule, OnInit} from "@angular/core";

import {Router} from "@angular/router";
import {NzModalService, NzModalSubject, NzNotificationService, UploadFile} from "ng-zorro-antd";
import * as moment from "moment";
import {HttpServcie} from "../../../service/http.service";
import {Config} from "../../../service/config";
import {DemandMaintenanceBean} from "../bean/demandMaintenance.bean";


@Component({
  selector: "demandMaintenance-page",
  templateUrl: "demandMaintenance.html",
  styleUrls: ["demandMaintenance.scss"]
})

export class DemandMaintenancePage {
  constructor(
    private httpService: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
    this.user = JSON.parse(window.localStorage.getItem("user"));
  }

  //业务参数
  applyStatus = Config.APPLY_STATUS;  //按需维保申请状态
  demandMaintenance : DemandMaintenanceBean = new DemandMaintenanceBean();
  user : any;
  data: Array<any> = [];
  partyType : string = "";
  maintanceFileList : UploadFile[] = []; //维保申明文件
  letterFileList : UploadFile[] = []; //承诺书照片
  uploadType : any;
  isVisible : boolean = false;

  startDate : string = "";
  endDate : string = "";
  planName : string = "";
  planType : string = "";
  //返回的集合
  dataList : any = [];

  //多选框参数
  allChecked: any = false;
  indeterminate: any = false;
  updateData: any = {};
  total = 0;

  //模态框参数
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;

  //其他参数
  config = Config;

  ngOnInit(){
    this.user = JSON.parse(window.localStorage.getItem("user"));
    this.partyType = this.user.partyType;
    this.demandMaintenance.pageSize = 10;
    this.demandMaintenance.currentPage = 1;
    this.query();
  }

  query(){
    if(this.demandMaintenance.startDate){
      this.demandMaintenance.startDate = moment(this.demandMaintenance.startDate).format("YYYY-MM-DD");
    }
    if(this.demandMaintenance.endDate){
      this.demandMaintenance.endDate = moment(this.demandMaintenance.endDate).format("YYYY-MM-DD");
    }
    if(this.partyType == '2'){
      this.demandMaintenance.userPartyId = this.user.partyId;
    }
    if(this.partyType == '1'){
      this.demandMaintenance.maintenancePartyId = this.user.partyId;
    }
    this.httpService.queryDemandMaintence(this.demandMaintenance).subscribe(data =>{
      if(data.status == '200'){
        this.dataList = data.data.list;
        this.total = data.data.total;
      }else{
        this._notification.create('error', '错误提示', data.message);
      }
    });
  }

  /**
   * 1：维保单位服务申明文件上传， 2：盖章后的承诺书文件上传
   */
  upload(data,flag){
    this.updateData = data;
    this.uploadType = flag;
    this.isVisible = true;
    if(flag == 1){
      this.maintanceFileList = [];
      if(data.maintenceServiceStatementDoc){
        (data.maintenceServiceStatementDoc + "").split(',').forEach(ele => {
          let file: UploadFile = {
            thumbUrl: this.config.IP +
              this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.maintanceFileList.push(file);
        })
      }
    }

    if(flag == 2){
      this.letterFileList = [];
      if (data.letterOfCommitmentDoc) {
        (data.letterOfCommitmentDoc + "").split(',').forEach(ele => {
          let file: UploadFile = {
            thumbUrl: this.config.IP +
              this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111,
            name: ele,
            type: 'image/png',
            response: {
              data: ele
            }
          }
          this.letterFileList.push(file);
        })
      }
    }

  }

  nzRemoveFile = (file: UploadFile) => {
    this.httpService.deleteUpload(file["response"]["data"]).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", "删除失败！");
          return;
        }
        if (this.maintanceFileList.length == 1) {
          this.maintanceFileList = [];
          return;
        }
        this.maintanceFileList.forEach((element, index) => {
          if (element["thumbUrl"] == file.thumbUrl) {
            this.maintanceFileList.splice(index, 1);
          }
        });
      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  };

  /**
   * 查看电梯详情
   */
  detail(data){
    this.router.navigate(["/home/demandMaintenanceElevator",{"elevatorIds" : data.elevatorIds}]);
  }
  /**
   * 1：下载服务申明文件，2：下载承诺书照片
   */
  downloadFile(data,flag){
    if(flag == 1){
      if (!data.maintenceServiceStatementDoc) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.maintenceServiceStatementDoc.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '维保服务标准自我申明' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
    if(flag == 2){
      this.httpService.demandExportFile(data).subscribe(data => {
        if(data.fileUrl){
          this.download(data.fileUrl, data.fileName);
        }else{
          this._notification.create("error", "提示", "没有文件");
          return;
        }

      });
    }
  }

  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }
  add(title, content, footer){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 2) {
      this._notification.create("error", "错误提示", "您无权限");
      return;
    }
    this.modelTitle = "添加";
    this.modal = 0;

    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  update(title, content, footer){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 2) {
      this._notification.create("error", "错误提示", "您无权限");
      return;
    }
    this.modelTitle = "修改";
    this.modal = 1;
    const updateList: any = [];

    this.dataList.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = element;
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("error", "错误提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "请选中一条数据！");
      return;
    }
    if(this.updateData.applyStatus != '1'){
      this._notification.create("error", "错误提示", "已审批的记录不能被修改！");
      return;
    }
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  submit(){
    const updateList: any = [];
    let demandMaint: DemandMaintenanceBean = new DemandMaintenanceBean();
    this.dataList.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = element;
      }
    });

    if (updateList.length > 1) {
      // 异常
      this._notification.create("error", "错误提示", "只能选中一条数据！");
      return;
    }

    if(updateList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "请选中一条数据！");
      return;
    }

    if(this.updateData.applyStatus != '0'){
      this._notification.create("error", "错误提示", "选中的记录已提交！");
      return;
    }
    if(!this.updateData.elevatorIds){
      this._notification.create("error", "错误提示", "请先添加参加按需维保的电梯！");
      return;
    }
    if(!this.updateData.maintenceServiceStatementDoc){
      this._notification.create("error", "错误提示", "请维保单位上传维保服务申明！");
      return;
    }
    if(!this.updateData.letterOfCommitmentDoc){
      this._notification.create("error", "错误提示", "请上传盖章后的承诺书文件照片！");
      return;
    }
    updateList.forEach(ele => {
      demandMaint.id = ele.id;
      demandMaint.applyStatus = '1'; //提交审批后，状态变成审批中
      demandMaint.parentPartyId = ele.parentPartyId;
      demandMaint.userPartyId = ele.userPartyId;
    });
    this.httpService.updateDemandMaintence(demandMaint).subscribe(data => {
      if (data["status"] == "200") {
        this._notification.create("success", "提示", "提交成功！");
        this.query();
      }else{
        this._notification.create("error", "错误提示", "提交失败！");
      }
    });
  }


  delete(){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 2) {
      this._notification.create("error", "错误提示", "您无权限");
      return;
    }
    const deleteList: any = [];
    const thiss: any = this;
    this.dataList.forEach(element => {
      if (element.checked) {
        deleteList.push(element.id);
      }
    });

    if (deleteList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "请选中一条数据！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpService.deleteDemandMaintence({ ids: deleteList }); //批量删除
        ob.subscribe(
          data => {
            if (data.status == "200") {
              thiss.demandMaintenance.currentPage = 1;
              thiss.query();
            } else {
              this._notification.create("error", "错误提示", data.message);
            }
          },
          error => {
            this._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() { }
    });
  }

  /**
   * 是否中止按需维保
   */
  isSuspend(data){
   let demandMaintenance : DemandMaintenanceBean = new DemandMaintenanceBean();
    demandMaintenance.id = data.id;
    demandMaintenance.applyStatus = '4';
    demandMaintenance.maintenancePartyId = data.maintenancePartyId;
    demandMaintenance.userPartyId = data.userPartyId;
    demandMaintenance.parentPartyId = data.parentPartyId;
    demandMaintenance.elevatorIds = data.elevatorIds;
    this.httpService.updateDemandMaintence(demandMaintenance).subscribe(data => {
      if (data["status"] == "200") {
        this._notification.create("success", "提示", "按需维保已中止！");
        this.query();
      }else{
        this._notification.create("error", "错误提示", "操作失败！");
        return;
      }
    });
  }

  displayDataChange($event){
    this.dataList = $event;
    this.refreshStatus();
  }

  checkAll(value){
    if (value) {
      this.dataList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.dataList.forEach(data => data.checked = false);
    }
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.dataList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.dataList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //分页处理
  nzPageSizeChange(event){
    this.demandMaintenance.pageSize = event;
    this.demandMaintenance.currentPage = 1;
    this.query();
  }

  nzPageIndexChange(event){
    this.demandMaintenance.currentPage = event;
    this.query();
  }

  nzPageIndexClickChange(event){
    this.demandMaintenance.currentPage = event;
    this.query();
  }

  //添加返回
  addCall(event) {
    this.currentModal.destroy();
    this.query();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  uploadChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "上传成功");
      }
      // Get this url from response in real world.
    }
  }

  //上传文件完成后的回调
  nzChangeFile(event) {
    if (event.file.status == "error") {
      this._notification.blank("上传失败", `${event.file.message}`);
    }
    if (event.file.status == "done") {
      if (this.uploadType == 2) {
        this.letterFileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }
    }
  }

  //上传完了之后 提交数据
  updateUpload() {
    if (this.uploadType == 1) {
      let param = {
        id: this.updateData.id,
        maintenceServiceStatementDoc : null
      }
      let list = [];
      this.maintanceFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.maintenceServiceStatementDoc = list.join(',');

      this.httpService.updateDemandMaintence(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.maintanceFileList = [];
          this.query();
        }
      });
    }

    if(this.uploadType == 2){
      let param = {
        id: this.updateData.id,
        letterOfCommitmentDoc : null
      }
      let list = [];
      this.letterFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.letterOfCommitmentDoc = list.join(',');

      this.httpService.updateDemandMaintence(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.letterFileList = [];
          this.query();
        }
      });
    }
  }

}
